import { storage } from '@/utils/storage.js'
import { defineStore } from 'pinia'

const useAppStore = defineStore('App', () => {
  //   color theme
  const prefersColorScheme = window.matchMedia('(prefers-color-scheme: dark)')
  const colorScheme = ref('light')

  //   language
  const navigatorLanguage = navigator.language
  const systemLanguage = navigatorLanguage === 'zh-CN' ? navigatorLanguage : navigatorLanguage.split('-')[0]
  const language = ref(storage.get('language') || systemLanguage)

  //   reload
  const reloadFlag = ref(true)
  watch(() => colorScheme, updateTheme, {
    immediate: true,
  })

  function updateTheme() {
    if (colorScheme.value === '') {
      colorScheme.value = prefersColorScheme.matches ? 'dark' : 'light'
    }
    switch (colorScheme.value) {
      case 'light':
        document.documentElement.classList.remove('dark')
        break
      case 'dark':
        document.documentElement.classList.add('dark')
        break
    }
    storage.set('colorScheme', colorScheme.value)
  }

  function setColorScheme(color) {
    colorScheme.value = color
    updateTheme()
  }

  function setLanguage(lang) {
    storage.set('language', lang)
    language.value = lang
  }

  async function reloadPage(duration = 200) {
    reloadFlag.value = false
    await nextTick()
    if (duration) {
      setTimeout(() => {
        reloadFlag.value = true
      }, duration)
    }
    else {
      reloadFlag.value = true
    }
    setTimeout(() => {
      document.documentElement.scrollTo({ left: 0, top: 0 })
    }, 100)
  }

  return {
    colorScheme,
    language,
    reloadFlag,
    setColorScheme,
    setLanguage,
    reloadPage,
  }
})
export default useAppStore
